if (typeof(Common) == "undefined") Common = {};

/**
 * Constructor expects single argument containing map of
 * message names => message contents for current locale.
 */
Common.LanguageUtils = function(msgMap) {
	this.msgMap = msgMap;
	
	return this;
};

Common.LanguageUtils.prototype = {
	msgMap: undefined,
	
	/**
	 * get a message. First argument should always be the name of the message.
	 * If the message is parameterized, you can pass either a second argument
	 * as an array containing the parameters, or pass each parameter as additional
	 * arguments.
	 * 
	 * <h3>Example:</h3>
	 * 
	 * In your resource file you have:
	 * <code>hello-world=Hello, {0}. Goodbye, {1}.</code>
	 * 
	 * In JavaScript:
	 * <code>portletMessages.getMessage("hello-world", "Bob", "Sally")</code>
	 * and
	 * <code>portletMessages.getMessage("hello-world", ["Bob", "Sally"])</code>
	 * are equivalent.
	 */
	getMessage: function(messageName) {
		if ( !messageName || messageName === undefined ) {
			throw "Must specify a messageName";
		}
	
		msg = this.msgMap[messageName];
		
		if ( !msg || msg == undefined ) {
			return messageName;
		}
		
		/* do parameter substitution */
		if ( arguments.length > 1 ) {
			var params;
			if ( arguments.length === 2 && arguments[1].constructor.toString().indexOf("Array") != -1 ) {
				params = arguments[1];
			} else {
				params = jQuery.makeArray(arguments).slice(1);
			}
			
			for ( var i = 0; i < params.length; i++ ) {
				msg = msg.replace(new RegExp('\\{' + i.toString() + '\\}', 'g'), params[i]);
			}
		}
		return msg;
	}
};